<template>
<a-modal
  v-model:visible="_d.visible"
  :title="_d.config.title"
  :ok-text="_d.config.okText"
  :cancel-text="_d.config.cancelText"
  @ok="handleOk"
  @cancel="handleCancel"
  :mask-closable="false"
  :keyboard="false">
  <a-form class="t-form" ref="formRef" :model="_d.form" layout="vertical">
    <a-form-item v-for="(item, index) in _d.config.fields" :key="index" :label="item.label" :name="item.name" :rules="item.rules">
      <a-input
        v-if="item.type === 'text' || item.type === 'password'"
        v-model:value="_d.form[item.name]"
        :type="text"
        :placeholder="item.placeholder"
        :auto-focus="true"
        @focus="changeInputType($event, item)"
      />
      <a-textarea
        v-else-if="item.type === 'textarea'"
        v-model:value="_d.form[item.name]"
        :placeholder="item.placeholder"
        :rows="4"
        :auto-size="{ minRows: 4, maxRows: 8 }"
        autocorrect="off"
        autocomplete="off"
        autocapitalize="off"
        spellcheck="false"
      />
    </a-form-item>
  </a-form>
</a-modal>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue';

const formRef = ref(null);

// 默认配置
const defaultConfig = () => ({
  title: '系统提示',
  fields: [
    {
      label: '',
      type: 'text',
      name: '',
      placeholder: '请输入内容',
      rules: [],
    }
  ],
  okText: '确定',
  cancelText: '取消',
  onOk: () => {},
  onCancel: () => {}
})

const _d = reactive({
  visible: false,
  form: {},
  config: defaultConfig()
})


// 显示弹窗
const show = (userConfig) => {
  // 重置表单
  _d.form = {};
  // 归一化
  if(!userConfig.fields) {
    userConfig.fields = [
      {
        label: userConfig.label || '',
        type: userConfig.type || 'type',
        name: userConfig.name || 'value',
        placeholder: userConfig.placeholder || '请输入内容',
        rules: userConfig.rules || []
      }
    ]
  }
  
  // 合并配置
  Object.assign(_d.config, defaultConfig(), userConfig);
  console.log(_d.config)
  
  _d.visible = true;
  
  // 清除之前的验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
};

// 确定按钮处理
const handleOk = () => {
  formRef.value.validate().then(() => {
    _d.config.onOk(_d.form);
    _d.visible = false;
  }).catch(error => {
    console.log('验证失败', error);
  });
};

// 取消按钮处理
const handleCancel = () => {
  _d.config.onCancel();
  _d.visible = false;
};

const changeInputType = (e, item) => {
  if(item.type == 'password') {
    e.target.type = 'password';
  }
}

// 暴露给父组件调用
defineExpose({ show });
</script>
<style scoped>
.t-form {
	padding: 24px 20px 0;
}	
</style>
